import {
  setStorage,
  getStorage,
  removeStorage,
  clearStorage
} from '@/utils/localStorage'


const state = {
  userInfo: getStorage('userInfo') || {}
}

const mutations = {
  LOGIN_SUCCESS (state, data) {
    setStorage('userInfo', data)
    state.userInfo = data
  },
  LOGIN_ERROR (state) {
    removeStorage('userInfo')
    clearStorage()
    state.userInfo = {}
  },
  LOG_OUT (state) {
    removeStorage('userInfo')
    clearStorage()
    state.userInfo = {}
  }
}

const actions = {
  loginSuccess ({ commit }, data) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async resolve => {
      commit('LOGIN_SUCCESS', data)
      resolve(data)
    })
  },
  loginOut ({ commit, state, dispatch }) {
    commit('LOG_OUT')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
